//
//  VideoCacheView.swift
//  Motion
//
//  Created by 悦月越悦 on 2021/3/16.
//

import SwiftUI

struct VideoCacheView: View {
    @ObservedObject var videoCacheModel = VideoCacheModel()
    
    var body: some View {
        NavigationLink(destination: VideoPlayView(),isActive: $videoCacheModel.complete){
            VStack{
                HStack{
                    Image("Motion")
                        .rectImage(56, 64)
                    Spacer()
                }
                .padding(.horizontal,14)
                Image("run")
                    .rectImage(280, 300)
                Text("正在为你加速下载中......")
                    .customFont(20, true)
                
                Spacer()
                DownloadProgress()
                
            }
        }
        .environmentObject(videoCacheModel)
    }
}

struct DownloadProgress:View{
    @EnvironmentObject var videoCacheModel: VideoCacheModel
    
    var body: some View{
        ZStack{
            ProgressView(value: videoCacheModel.downloadSize/videoCacheModel.totalSize, total: 1)
                .progressViewStyle(MyProgressViewStyle(foregroundColor: Color("topicPurple"), backgroundColor: Color("topicPurple").opacity(0.5)))
                .frame(height: 100)
            Text("下载\(String(format:"%.1f", videoCacheModel.downloadSize))MB/\(String(format:"%.1f", videoCacheModel.totalSize))MB")
                .customFont(20, true)
                .foregroundColor(.white)
        }.onAppear(perform: {
            videoCacheModel.fetchActionListAndDownloadVideo()
        })
    }
}

//进度条
struct MyProgressViewStyle:ProgressViewStyle{
    let foregroundColor:Color
    let backgroundColor:Color
    init(foregroundColor:Color,backgroundColor:Color){
        self.foregroundColor = foregroundColor
        self.backgroundColor = backgroundColor
    }
    func makeBody(configuration: Configuration) -> some View {
        GeometryReader{ proxy in
            ZStack(alignment:.topLeading){
            backgroundColor
            Rectangle()
                .fill(foregroundColor)
                .frame(width:proxy.size.width * CGFloat(configuration.fractionCompleted ?? 0.0),height: proxy.size.height)
            }
            .frame(height:proxy.size.height)
        }
    }
}

struct VideoCacheView_Previews: PreviewProvider {
    static var previews: some View {
        VideoCacheView()
    }
}
